package com.sise.bl.service.impl;

import com.sise.bl.dao.AddressDao;
import com.sise.bl.entity.Address;
import com.sise.bl.entity.User;
import com.sise.bl.service.AddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

@Transactional
@Service(value = "addressService")
public class AddressServiceImpl implements AddressService {
    @Autowired
    @Qualifier(value = "addressDao")
    private AddressDao addressDao;

    @Override
    public List<Address> findAddressByUid(Integer uid) {
        //根据用户id查询该用户所有地址
        List<Address> addresses = addressDao.selectAddressByUid(uid);
        return addresses;
    }

    @Override
    public int saveAddress(Address address) {
        int i = addressDao.insertAddress(address);
        return i;
    }

    @Override
    public void deleteAddressByAid(String aid) {
        //根据地址id查询该地址
        Address address = addressDao.selectByAid(Integer.valueOf(aid));
        addressDao.deleteAddressByAid(address);
    }

    @Override
    public void setAddressToDefault(String aid, Integer uid) {
        //查询默认地址
        List<Address> objects = addressDao.selectStateDefault();
        if (objects.size() > 0) {  //默认地址存在
            Address address = objects.get(0);
            address.setAstate(0);  //修改默认地址为普通地址
            addressDao.updateAddressByAid(address);
        }
        // 将需要的普通地址，设置为默认地址
        Address address = addressDao.selectByAid(Integer.valueOf(aid));
        address.setAstate(1);
        addressDao.updateAddressByAid(address);

    }

    @Override
    public void updateByAid(@RequestParam Address address) {
        addressDao.updateAddressByAid(address);
    }
}
